package com.ohuang.signatureinfo

import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.ohuang.signatureinfo.share.Share2
import com.ohuang.signatureinfo.share.ShareContentType
import com.ohuang.signatureinfo.ui.theme.SignatureInfoTheme
import kotlinx.coroutines.launch
import java.util.Arrays

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SignatureInfoTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Greeting(copy = {
                        ClipboardUtils.copyText(it,this@MainActivity)

                    }, share = {
                        val path=this@MainActivity.cacheDir.absolutePath + "/signatureInfo.txt"
                        FileUtils.writeText(
                            path,
                            it
                        )
                        share(path)
                    }, tip = {
                        Toast.makeText(this@MainActivity, it, Toast.LENGTH_LONG).show()
                    })
                }
            }
        }
    }

    private fun share(path: String) {
        val uriForFile = MyFileProvider.getUriForFile(
            this,
            path
        )
        Share2.Builder(this).setContentType(ShareContentType.FILE)
            .setShareFileUri(uriForFile).build().shareBySystem()
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Greeting(copy: (String) -> Unit, share: (String) -> Unit, tip: (String) -> Unit) {
    var rememberScrollState = rememberScrollState()

    Column(modifier = Modifier.verticalScroll(rememberScrollState)) {
        val packeName = remember {
            mutableStateOf<String>("")
        }
        val txt = remember {
            mutableStateOf<String>("")
        }
        TextField(value = packeName.value, onValueChange = {
            packeName.value = it
        })

        Row {
            Signature(packeName=packeName.value, tip=tip, txt=txt, text = "获取签名", type = 0)
            Signature( packeName=packeName.value,tip= tip,txt= txt, text = "获取签名md5", type = 1)
        }
        Row {
            Signature( packeName=packeName.value,tip= tip,txt= txt, text = "获取签名SHA1", type = 2)
            Signature( packeName=packeName.value,tip= tip,txt= txt, text = "获取签名SHA-256", type = 3)
        }

        Row {
            Button(onClick = { share(txt.value) }) {
                Text(text = "分享为文件")
            }
            Button(onClick = { copy(txt.value) }) {
                Text(text = "复制内容")
            }
        }
        Text(text = txt.value)
    }
}

@Composable
private fun Signature(
    packeName: String,
    tip: (String) -> Unit,
    txt: MutableState<String>,
    text:String,
    type:Int=0 // 0:签名数据 1:签名md5 2:sha1 3:sha256
) {
    var rememberCoroutineScope = rememberCoroutineScope()
    var content = LocalContext.current
    Button(onClick = {
        rememberCoroutineScope.launch {
            try {
                val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    content.packageManager.getPackageInfo(
                        packeName,
                        PackageManager.GET_SIGNING_CERTIFICATES
                    )
                } else {
                    content.packageManager.getPackageInfo(
                        packeName,
                        PackageManager.GET_SIGNATURES
                    )
                }
                if (packageInfo == null) {
                    tip("PackageInfo not found")
                    txt.value = "PackageInfo not found"
                } else {
                    val stringBuffer = StringBuffer()
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {

                        packageInfo.signingInfo.signingCertificateHistory.forEachIndexed { index, signature ->
                            val data=when(type){
                                0->Arrays.toString(signature.toByteArray())
                                1->{
                                    DigestUtil.getMD5(signature.toByteArray())}
                                2->{
                                    DigestUtil.getSHA1(signature.toByteArray())
                                }
                                3->{
                                    DigestUtil.getSHA256(signature.toByteArray())
                                }
                                else -> {Arrays.toString(signature.toByteArray())}
                            }
                            stringBuffer.append("\nsignatures[$index]=").append("\n")
                                .append(data)
                        }
                    } else {
                        packageInfo.signatures.forEachIndexed { index, signature ->
                            val data=when(type){
                                0->Arrays.toString(signature.toByteArray())
                                1->{
                                    DigestUtil.getMD5(signature.toByteArray())}
                                2->{
                                    DigestUtil.getSHA1(signature.toByteArray())
                                }
                                3->{
                                    DigestUtil.getSHA256(signature.toByteArray())
                                }
                                else -> {Arrays.toString(signature.toByteArray())}
                            }
                            stringBuffer.append("\nsignatures[$index]=").append("\n")
                                .append(data)
                        }
                    }
                    txt.value = stringBuffer.toString()
                }
            } catch (e: Exception) {
                txt.value = e.toString()
            }
        }
    }) {
        Text(text = text)
    }
}

